package gson.gson.Interface;

import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import model.User;

import java.io.IOException;

/**
 * 自定义 TypeAdapterFactory 实现
 */
public class CustomTypeAdapterFactory implements TypeAdapterFactory {

    @Override
    public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
        if (!type.getRawType().equals(User.class)) {
            return null; // 不处理非目标类型
        }

        // 创建并返回自定义的 TypeAdapter
        return new TypeAdapter<T>() {

            @Override
            public void write(JsonWriter out, T value) throws IOException {
                // 自定义序列化逻辑
                User user = (User) value;
                out.beginObject();
                out.name("user_name").value(user.getUserName());
                out.name("user_age").value(user.getAge());
                out.endObject();
            }

            @Override
            public T read(JsonReader in) throws IOException {
                // 自定义反序列化逻辑
                in.beginObject();
                String userName = null;
                int age = 0;

                while (in.hasNext()) {
                    String name = in.nextName();
                    if (name.equals("user_name")) {
                        userName = in.nextString();
                    } else if (name.equals("user_age")) {
                        age = in.nextInt();
                    }
                }
                in.endObject();
                return (T) new User(userName, age, null);
            }
        };
    }
}
